package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description: 订单定时处理任务
 * @author: nianqiang
 * @Version: V1.0
 */
@Slf4j
@Component   // 组件扫描,为当前类创建实例化对象,执行任务
public class OrderTask {

		@Autowired
		private OrderMapper orderMapper;

		/**
		 * 超过15分钟未支付的订单,取消订单处理
		 */
		@Scheduled(cron = "0 0/1 * * * ?")
		public void processTimeoutOrder() {
				log.info(">>>>> OrderTask processTimeoutOrder is running <<<<<<");
				//1 查询 超过15分钟 未支付的订单
				// 查询超过15分钟  当前时间 - 15min = 时间 和 创建订单时间比较
				LocalDateTime orderTime = LocalDateTime.now().minusMinutes(15);
				List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.PAID, orderTime);

				//2 遍历订单集合, 修改订单的状态为6(已取消)
				for (Orders orders : ordersList) {
						// 修改订单状态 6(已取消)
						orders.setStatus(Orders.CANCELLED);
						orders.setCancelTime(LocalDateTime.now());
						orders.setCancelReason("订单超时未支付");

						orderMapper.update(orders);

						// 恢复库存
				}
				log.info(">>>>> OrderTask processTimeoutOrder is success <<<<<<");
		}



		/**
		 * 商家点击完成订单操作
		 */
		@Scheduled(cron = "0 0 1 * * ?")
		public void processDeliveryOrder() {
				log.info(">>>>> OrderTask processDeliveryOrder is running <<<<<<");
				//1 查询 超过15分钟 未支付的订单
				// 查询超过15分钟  当前时间 - 1h = 时间 和 创建订单时间比较
				LocalDateTime orderTime = LocalDateTime.now().minusHours(1);
				List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, orderTime);

				//2 遍历订单集合, 修改订单的状态为6(已取消)
				for (Orders orders : ordersList) {
						// 修改订单状态 6(已取消)
						orders.setStatus(Orders.COMPLETED);
						orderMapper.update(orders);

						// 恢复库存
				}
				log.info(">>>>> OrderTask processDeliveryOrder is success <<<<<<");
		}

}
